package com.changgou.order.controller;

import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.order.config.TokenDecode;
import com.changgou.order.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 *  购物车业务接口
 */
@RestController
@RequestMapping("/cart")
public class CartController {

    @Autowired
    private CartService cartService;

    @Autowired
    private TokenDecode tokenDecode;

    /**
     * 添加商品到购物车接口
     * @param skuId 添加商品的库存id
     * @param num   购买数量
     * @return
     */
    @GetMapping("/add/{skuId}/{num}")
    public Result add(@PathVariable(value = "skuId") String skuId, @PathVariable(value = "num")Integer num) {
        //获取当前登录用户的用户名
        Map<String, String> userInfo = tokenDecode.getUserInfo();
        String username = userInfo.get("username");

        //调用service 添加商品到购物车
        cartService.add(skuId, num, username);
        return new Result(true, StatusCode.OK, "添加商品到购物车成功");
    }

    /**
     * 查询购物车列表
     * @return
     */
    @GetMapping("/list")
    public Map<String, Object> list() {
        //1. 获取当前登录用户的用户名
        Map<String, String> userInfo = tokenDecode.getUserInfo();
        String username = userInfo.get("username");

        //2. 调用service获取这个用户的购物车列表返回
        Map<String, Object> map = cartService.list(username);
        return map;
    }

    /**
     * 删除
     * @param skuId
     * @return
     */
    @GetMapping("/delete")
    public Result delete(@RequestParam(value = "skuId") String skuId) {
        //1. 获取当前登录用户的用户名
        Map<String, String> userInfo = tokenDecode.getUserInfo();
        String username = userInfo.get("username");

        //2. 调用service删除
        cartService.delete(username, skuId);

        return new Result(true, StatusCode.OK, "删除成功");
    }

    /**
     * 购物车列表复选框状态, 勾选与取消勾选
     * @param skuId     勾选商品的库存id
     * @param checked   勾选与取消勾选状态
     * @return
     */
    @GetMapping("/updateChecked")
    public Result updateChecked(@RequestParam(value = "skuId") String skuId,
                                @RequestParam(value = "checked")Boolean checked) {
        //1. 获取当前登录用户的用户名
        Map<String, String> userInfo = tokenDecode.getUserInfo();
        String username = userInfo.get("username");

        //2. 调用service修改复选框状态
        cartService.updateChecked(username, skuId, checked);

        return new Result(true, StatusCode.OK, "修改状态成功");
    }
}
